-module(dictionary_server).
-export([start/0, stop/0, insert/2, remove/1, lookup/1, clear/0, size/0]).

%%D:/Danielle/Quarter 3/INF 102/102Workspace/Assignment3

%%start
start() -> 
	register(dictionaryserver, 
    spawn(fun() -> run([]) end)).
	
%%stop
stop() -> io:fwrite("stop").

%%insert does not allow you to update a key
insert(Key, Value) -> 
  dictionaryserver ! {self(), {insert, Key, Value}},
	receive
	  {dictionary_server_result, Result} ->
		Result
  end.
  
%%remove is wonky
remove(Key) -> 
 dictionaryserver ! {self(), {remove, Key}},
   receive
     {dictionary_server_result, Result} ->
       Result
   end.

%%lookup
lookup(Key) -> 
  dictionaryserver ! {self(), {lookup, Key}},
  	receive
  	  {dictionary_server_result, false} ->
  	    notfound;
  	  {dictionary_server_result, {value, {Key, Value}}} ->
  	    {ok, Value}
   	end.

%%clear
clear() -> 
  dictionaryserver ! {self(), {clear}},
  	receive
  	  {dictionary_server_result, Result} ->
  	    Result
  	end.

%%size
size() -> 
  dictionaryserver ! {self(), {size}},
  	receive
  	  {dictionary_server_result, Result} ->
  	    Result
  	end.

%%run
run(L) ->
  receive
    {ResponsePid, {insert, Key, Value}} ->
      M = lists:keystore(Key, 2, L, {Key, Value}),
      respond(ResponsePid, M),
      run(M);
      
    {ResponsePid, {lookup, Key}} ->
      N = lists:keysearch(Key, 1, L),
      respond(ResponsePid, N),
      run(L);
      
    {ResponsePid, {clear}} ->
      O = [],
      respond(ResponsePid, O),
      run(O);
      
    {ResponsePid, {remove, Key}} ->
      P = lists:keytake(Key, 1, L),
      respond(ResponsePid, P),
      run(P);
      
    {ResponsePid, {size}} ->
      respond(ResponsePid, length(L)),
      run(L);
      
    {ResponsePid, stop} ->
      respond(ResponsePid, ok)
  end.

%%respond
respond(ResponsePid, Result) ->
	ResponsePid ! {dictionary_server_result, Result}.
	
	
	
	
	
	
	
	
	